package com.avic.rong.questionOrAnswer.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.questionOrAnswer.DialogShare;
import com.avic.rong.questionOrAnswer.ShareUtilCallBack;
import com.avic.rong.questionOrAnswer.api.AnswerThumbNumApi;
import com.avic.rong.questionOrAnswer.api.CancelThumbApi;
import com.avic.rong.questionOrAnswer.api.CancelnCollectionApi;
import com.avic.rong.questionOrAnswer.api.CollectApi;
import com.avic.rong.questionOrAnswer.api.DeleteAnswerApi;
import com.avic.rong.questionOrAnswer.api.ThumbApi;
import com.avic.rong.questionOrAnswer.api.UpdateDataAnswerApi;
import com.avic.rong.questionOrAnswer.bean.AnswerUpdataBean;
import com.avic.rong.questionOrAnswer.bean.WebAnswerBean;
import com.avic.rong.userOrder.api.AnswerCollectNumApi;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.SmartHttp;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.ScrollWebViewListion;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.tsy.sdk.myokhttp.response.IResponseHandler;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Response;
import wendu.dsbridge.OnReturnValue;

public class AnswerDetailsActivity extends BaseActivity implements ShareUtilCallBack {



    @BindView(R.id.btn_comment_publish)
    TextView btnCommentPublish;
    @BindView(R.id.btn_collect)
    ImageView btnCollect;
    @BindView(R.id.collect_number)
    TextView collectNumber;
    @BindView(R.id.btn_bottom_share)
    ImageView btnBottomShare;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.webview)
    ScrollWebViewListion web;
    @BindView(R.id.btn_zan)
    ImageView btnZan;
    @BindView(R.id.zan_number)
    TextView zanNumber;
    @BindView(R.id.rl_zan)
    RelativeLayout rlZan;
    @BindView(R.id.rl_collect)
    RelativeLayout rlCollect;
    private WebSettings settings;
    private String ansID;
    private WebAnswerBean webAnswerBean;
    private DialogShare dialogShare;
    private int COMMONT_REF = 1000;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_answer_details;
    }

    @Override
    protected void initView() {
        if (TextUtils.isEmpty(getIntent().getStringExtra("ansID"))) {
            finish();
            return;
        } else {
            ansID = getIntent().getStringExtra("ansID");
        }
        tvTitle.setText("回答详情");
        ivRight.setClickable(false);
        web.setInitialScale(100);
//        web.setWebChromeClient(new MyWebChromeClient());
//        web.setWebViewClient(new MyWebViewClient());


        settings = web.getSettings();


        // 设置加载进来的页面自适应手机屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);


        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);


        web.addJavascriptObject(this, null);
        web.setOnScrollChangeListener(new ScrollWebViewListion.OnScrollChangeListener() {
            @Override
            public void onPageEnd(int l, int t, int oldl, int oldt) {
                web.callHandler("loadMore", new OnReturnValue<String>() {
                    @Override
                    public void onValue(String retValue) {

                    }
                });
            }

            @Override
            public void onPageTop(int l, int t, int oldl, int oldt) {

            }

            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {

            }
        });

        web.loadUrl(AppUtils.BASE_URL + "answer/detail?ansId=" + ansID + "&token=" + URLEncoder.encode(getSharedPreferencesUtil().getLogintoken()));

        btnBottomShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享
                if (dialogShare == null) {
                    dialogShare = new DialogShare(AnswerDetailsActivity.this, AnswerDetailsActivity.this);
                }
                if (webAnswerBean != null) {
                    // FIXME: 2019/1/7 确认分享内容

                    answerNum(ansID);

                    if (webAnswerBean.getImgs() != null&&!TextUtils.isEmpty(webAnswerBean.getImgs().get(0)) && webAnswerBean.getImgs().size() > 0) {
                        List<String> imgs = webAnswerBean.getImgs();
                        dialogShare.showDialog(webAnswerBean.getTitle(), webAnswerBean.getDesc(), webAnswerBean.getUrl(), imgs.get(0));
                    } else {
                        dialogShare.showDialog(webAnswerBean.getTitle(), webAnswerBean.getDesc(), webAnswerBean.getUrl(),"");
                    }

                }
            }
        });
    }

    @JavascriptInterface
    public String getPage(Object msg) {
        Log.e("====initPage", "调用了" + msg);
        Gson gson = new Gson();
        webAnswerBean = gson.fromJson(msg.toString(), WebAnswerBean.class);
        if (webAnswerBean != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (webAnswerBean.isIsCollect()) {
                        btnCollect.setSelected(true);
                    } else {
                        btnCollect.setSelected(false);
                    }
                    if (webAnswerBean.isIsThumb()) {
                        btnZan.setSelected(true);
                    } else {
                        btnZan.setSelected(false);
                    }
                    zanNumber.setText(webAnswerBean.getNiceNum() + "");
                    collectNumber.setText(webAnswerBean.getCollectNum() + "");
                }
            });

        }

        web.callHandler("closeDeepLink", new OnReturnValue<String>() {
            @Override
            public void onValue(String retValue) {

            }
        });
//        handler.complete(getSharedPreferencesUtil().getLogintoken());
            return getSharedPreferencesUtil().getLogintoken();
    }

    @JavascriptInterface
    public void openQuestion(Object msg) {
        try {
            JSONObject jsonObject = new JSONObject(msg.toString());
            String queId = jsonObject.getString("queId");
            startActivity(QuestionDetailsActivity.queryIntent(this, queId));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void userLogin(Object msg) {
        if (!SharedPreferencesUtil.isLogin()) {
            startActivity(LoginPhoneActivity.queryIntent(this));
        }
    }

    @JavascriptInterface
    public void editAnswer(Object msg) {

        updateDataAnswer();
    }

    @JavascriptInterface
    public void delAnswer(Object msg) {
        DialogCustom.showDoubleDialog(this, "", "确定要删除当前已发布的回答吗？", "取消", "确定", new DialogCustom.CustomDialogDouble() {
            @Override
            public void rightButtonClicked() {
                deleteAnswer();
            }

            @Override
            public void leftButtonClicked() {

            }
        });


    }

    @JavascriptInterface
    public void openUserCenter(Object msg){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(msg.toString());
            String userId = jsonObject.getString("userId");
            Intent intent = new Intent(AnswerDetailsActivity.this, PersonalHomeActivity.class);
            intent.putExtra("homeUserID",userId);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    private void deleteAnswer() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            map.put("ansId", ansID);
            final DeleteAnswerApi deleteAnswerApi = new DeleteAnswerApi(this, simpleOnNextListenerDeleteQue);
            deleteAnswerApi.setCache(false);
            deleteAnswerApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(deleteAnswerApi);
        }
    }

    private void updateDataAnswer() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("ansId", ansID);
            final UpdateDataAnswerApi updateDataAnswerApi = new UpdateDataAnswerApi(this, simpleOnNextListenerUpdateDataQuestions);
            updateDataAnswerApi.setCache(false);
            updateDataAnswerApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(updateDataAnswerApi);
        }
    }

    //删除回答
    HttpOnNextListener simpleOnNextListenerDeleteQue = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(AnswerDetailsActivity.this, subjects.getMsg());
                return;
            }
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.DELETE_ANSWER_INFORM);
            EventBus.getDefault().post(informUpdate);
            finish();


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());

        }
    };
    //编辑回答
    HttpOnNextListener simpleOnNextListenerUpdateDataQuestions = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(AnswerDetailsActivity.this, subjects.getMsg());
                return;
            }
            AnswerUpdataBean answerUpdataBean = (AnswerUpdataBean) subjects.getData();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    startActivityForResult(AnswerActivity.queryIntent(AnswerDetailsActivity.this, answerUpdataBean),AnswerActivity.ANSWER_UPDATE);
                }
            });


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());

        }
    };


    @Override
    protected void addListener() {
        btnCommentPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
                    //发布评论页
                    Bundle bundle = new Bundle();
                    bundle.putString("contentId", ansID);
                    bundle.putString("contentType", "7");
                    enterPageForResult(PublishCommentActivity.class, bundle, COMMONT_REF);
                } else {
                    startActivity(LoginPhoneActivity.queryIntent(AnswerDetailsActivity.this));
                }

            }
        });


        rlCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnCollect.isSelected()) {
                    unCollectReq(Integer.parseInt(ansID), context);
                } else {
                    collectReq(Integer.parseInt(ansID), context);
                }
            }
        });
        rlZan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnZan.isSelected()){
                    unZanReq(Integer.parseInt(ansID),context);
                }else {
                    zanReq(Integer.parseInt(ansID),context);
                }
            }
        });
    }

    public static Intent queryIntent(Context context, String ansID) {
        Intent intent = new Intent(context, AnswerDetailsActivity.class);
        intent.putExtra("ansID", ansID);
        return intent;
    }

    private void collectReq(int contId, Context context) {
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(getSharedPreferencesUtil().getLogintoken())) {
            return;
        }
        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 14 + "");

        map.put("token", getSharedPreferencesUtil().getLogintoken());
        final CollectApi collectApi = new CollectApi(this, simpleOnNextListenerCollect);
        collectApi.setCache(false);
        collectApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(collectApi);
    }

    private void unCollectReq(int contId, Context context) {

        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(getSharedPreferencesUtil().getLogintoken())) {
            return;
        }

        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 14 + "");

        map.put("token", getSharedPreferencesUtil().getLogintoken());
        final CancelnCollectionApi cancelnCollectionApi = new CancelnCollectionApi(this, simpleOnNextListenerUnCollect);
        cancelnCollectionApi.setCache(false);
        cancelnCollectionApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(cancelnCollectionApi);
    }

    private void unZanReq(int contId, Context context) {

        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(getSharedPreferencesUtil().getLogintoken())) {
            return;
        }

        map.put("contId", contId + "");

        //新闻1提问2回答3
        map.put("type", 3 + "");

        map.put("token", getSharedPreferencesUtil().getLogintoken());
        final CancelThumbApi cancelThumbApi = new CancelThumbApi(this, simpleOnNextListenerUnZan);
        cancelThumbApi.setCache(false);
        cancelThumbApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(cancelThumbApi);


    }

    private void zanReq(int contId, Context context) {


        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(getSharedPreferencesUtil().getLogintoken())) {
            return;
        }

        map.put("contId", contId + "");
        //
        //新闻1提问2回答3
        map.put("type", 3 + "");
        map.put("token", getSharedPreferencesUtil().getLogintoken());
        final ThumbApi thumbApi = new ThumbApi(this, simpleOnNextListener);
        thumbApi.setCache(false);
        thumbApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(thumbApi);


    }

    //取消收藏
    HttpOnNextListener simpleOnNextListenerUnCollect = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "取消收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            collectNumber.setText(num + "");
            btnCollect.setSelected(false);
//            questionCollectNum();

            answerCollectNum();


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //收藏
    HttpOnNextListener simpleOnNextListenerCollect = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_1000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            collectNumber.setText(num + "");
            btnCollect.setSelected(true);
//            questionCollectNum();
            answerCollectNum();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

//    private void questionCollectNum() {
//
//        Map<String, String> map = new HashMap<>();
//
//        if (TextUtils.isEmpty(ansID)) {
//            return;
//        }
//        map.put("queId", ansID);
//
//        final QuestionCollectNumApi questionCollectNumApi = new QuestionCollectNumApi(this, simpleOnNextListenerCollectNum);
//        questionCollectNumApi.setCache(false);
//        questionCollectNumApi.setMap(map);
//        HttpManager.getInstance().doHttpDeal(questionCollectNumApi);
//    }

    //点赞
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "点赞成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            zanNumber.setText(num + "");
            btnZan.setSelected(true);
            thumbNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //取消点赞
    HttpOnNextListener simpleOnNextListenerUnZan = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

            ToastTools.showToast(context, "取消点赞成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            zanNumber.setText(num + "");
            btnZan.setSelected(false);
            thumbNum();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    private void thumbNum() {

        Map<String, String> map = new HashMap<>();

        if (TextUtils.isEmpty(ansID)) {
            return;
        }
        map.put("ansId", ansID);

        final AnswerThumbNumApi answerThumbNumApi = new AnswerThumbNumApi(this, simpleOnNextListenerThumbNum);
        answerThumbNumApi.setCache(false);
        answerThumbNumApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(answerThumbNumApi);
    }
    private void answerCollectNum() {
        Map<String, String> map = new HashMap<>();

        if (TextUtils.isEmpty(ansID)) {
            return;
        }
        map.put("ansId", ansID + "");

        final AnswerCollectNumApi answerCollectNumApi = new AnswerCollectNumApi(this, simpleOnNextListenerAnswerCollectNum);
        answerCollectNumApi.setCache(false);
        answerCollectNumApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(answerCollectNumApi);
    }

    //回答收藏变动
    HttpOnNextListener simpleOnNextListenerAnswerCollectNum = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //回答点赞数变动
    HttpOnNextListener simpleOnNextListenerThumbNum = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //问题收藏变动
    HttpOnNextListener simpleOnNextListenerCollectNum = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };


    @Override
    public void shareSuccess() {

    }

    @Override
    public void shareFailed() {

    }

    @Override
    public void shareCancel() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == COMMONT_REF && resultCode == PublishCommentActivity.RESULT_COMMENT_CODE) {
            web.callHandler("loadComment", new OnReturnValue<String>() {
                @Override
                public void onValue(String retValue) {

                }
            });
        }else if (requestCode == AnswerActivity.ANSWER_UPDATE && resultCode==RESULT_OK){
            web.reload();
        }
    }


    private void answerNum(String answerId){

        SmartHttp.getHttpTwo(AppUtils.BASE_URL + "answer/shareNum?ansId=" + answerId , new IResponseHandler() {
            @Override
            public void onSuccess(Response response) {
                Logger.i("----------onSuccess");
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Logger.i("----------onFailure");
            }

            @Override
            public void onProgress(long currentBytes, long totalBytes) {
                Logger.i("----------onProgress");
            }
        });

    }
}
